<template>
  <el-row>
    <el-col :sm="{span:10,offset:7}">
      <el-form :model="tag" :rules="rules" class="margin_bt" ref="tagsForm" label-width="80px">
        <el-form-item label="标签名称" prop="name">
          <el-input v-model="tag.name" placeholder="请输入标签名称"></el-input>
        </el-form-item>
        <el-form-item label="颜色" prop="color">
          <el-color-picker v-model="tag.color"></el-color-picker>
        </el-form-item>
        <el-form-item class="center">
          <el-button type="primary" @click="submit('tagsForm')">添加</el-button>
        </el-form-item>
      </el-form>
    </el-col>
  </el-row>
</template>

<script>
import {ElMessage} from 'element-plus'
import axios from 'axios'
export default {
  name: "addTypes",
  data() {
    return{
      tag: {
        name: '',
        color: '#00ff98',
        md5Password: ''
      },
      rules: {
        name: {required: true, message: '请输入标签名称', trigger: 'blur'}
      }
    }
  },
  mounted(){
    let id = this.$route.query.id;
    if ( id != undefined) {
      axios.get("/admin/selectOneTag",{params:{id:id}}).then( (res) => {
        this.tag = res.data
      })
    }
  },
  methods: {
    submit: function (tagsForm){
      this.$refs[tagsForm].validate( (valid) => {
        if ( valid ){
          this.tag.md5Password = localStorage.getItem("password");
          if ( this.$route.query.id === undefined){
            axios.post("/admin/addTag",this.tag).then( (res) => {
              if ( res.data === true){
                ElMessage.success("添加成功")
                this.$router.push({
                  name: 'tags'
                })
              }
              else
                ElMessage.error("添加失败")
            })
          }
          else {
            axios.post("/admin/updateTag", this.tag).then((res) => {
              if (res.data === true) {
                ElMessage.success("修改成功");
                this.$router.push({
                  name: 'tags'
                })
              } else {
                ElMessage.error("修改失败")
              }
            })
          }
        }else {
          console.log("失败")
        }
      })
    }
  }
}
</script>

<style scoped>
.center {
  text-align: center;

}
.margin_bt {
  margin: 50px 0;
}
</style>